package com.xiaoxiao.springbootstudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxiao.springbootstudy.pojo.Store;
import com.xiaoxiao.springbootstudy.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class StoreController {

    @Autowired
    private StoreService storeService;

    /*处理加载仓库选项的请求*/
    @GetMapping("/storeList")
    public List<Store> storeList(){
        QueryWrapper<Store> wrapper=new QueryWrapper<>();
        wrapper.select("store_id","store_name");
        return storeService.list(wrapper);
    }

    @GetMapping("/storePageList")
    public Map<String, Object> queryStoreList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Store> page = new Page<>(pageNum, pageSize);
        List<Store> storeList = storeService.list(page);

        Map<String, Object> result = new HashMap<>();
        result.put("total", page.getTotal());
        result.put("storeList", storeList);

        return result;
    }

    @GetMapping("/deleteStore/{id}")
    public Map<String, Object> deleteStore(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "操作失败");
        try {
            storeService.removeById(id);
            result.put("code", 200);
            result.put("msg", "删除仓库信息成功");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    @PostMapping("/saveStore")
    public Map<String, Object> saveStore(@RequestBody Store store) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "添加失败");

        try {
            storeService.save(store);
            result.put("code", 200);
            result.put("msg", "仓库添加成功");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return result;
    }
}